// ajax请求
let params = {
  pagenum: 3,
  pagesize: 3,
};

// 封装函数，获取文章，渲染到tbody中
function renderArticle() {
  axios.get(`/my/article/list`, { params }).then((res) => {
    // console.log(res);
    let { status, data, total } = res.data;
    // console.log(res.data);
    if (status === 0) {
      let str = "";
      data.forEach((item) => {
        str += `
        <tr>
                <td>${item.title}</td>
                <td>${item.cate_name}</td>
                <td>${item.pub_date}</td>
                <td>${item.state}</td>
                <td>
                  <button type="button" class="layui-btn layui-btn-xs">
                    编辑
                  </button>
                  <button
                    type="button"
                    class="layui-btn layui-btn-xs layui-btn-danger"
                  >
                    删除
                  </button>
                </td>
              </tr>
        `;
      });
      $("tbody").html(str);
      showPage(total);
    }
  });
}
renderArticle();

// 分页
let laypage = layui.laypage;

function showPage(t) {
  laypage.render({
    elem: "page",
    count: t,
    limit: params.pagesize,
    curr: params.pagenum,
    limits: [2, 3, 5, 10],
    layout: ["limit", "prev", "page", "next", "count", "skip"],
    jump: function (obj, first) {
      if (!first) {
        params.pagenum = obj.curr;
        params.pagesize = obj.limit;
        renderArticle();
      }
    },
  });
}

// 筛选
axios.get("/my/category/list").then((res) => {
  let { status, data } = res.data;
  if (status === 0) {
    let str = "";
    data.forEach((item) => {
      str += `<option value="${item.id}">${item.name}</option>`;
    });
    $("#category").append(str);
    let form = layui.form;
    form.render("select");
  }
});

// 完成筛选
$("#search").on("submit", function (e) {
  e.preventDefault();
  let cate_id = $("#category").val();
  let state = $("#state").val();
  // console.log(state);
  if (cate_id) {
    params.cate_id = cate_id;
  } else {
    delete params.cate_id;
  }
  if (state) {
    params.state = state;
  } else {
    delete params.state;
  }
  params.pagenum = 1;

  renderArticle();
});
